package com.hfzy.ihk.web.calldata.biz;

import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.core.elasticsearch.service.EsBaseServiceImpl;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.calldata.entity.CallHistoryText;
import com.hfzy.ihk.facade.calldata.enums.CallDataRedisVersionKey;
import com.hfzy.ihk.facade.calldata.enums.CallDataTables;
import com.hfzy.ihk.web.calldata.dao.CallHistoryTextRepository;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SourceFilter;
import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2018/8/22.
 */
@Component
public class CallHistoryTextBiz extends EsBaseServiceImpl<CallHistoryText>{

    @Autowired
    CallHistoryTextRepository callHistoryTextRepository;

    @Override
    protected ElasticsearchCrudRepository getReposity() {
        return callHistoryTextRepository;
    }

    /**
     * 新增通话内容
     * @param callHistoryText
     * @return
     */
    public WebResult saveCallHistoryText(CallHistoryText callHistoryText){
        WebResult result = new WebResult();
        boolean flag = createDataAndSetVersion(CallDataRedisVersionKey.TABLE_CALL_HISTORY_TEXT,
                CallDataTables.CALL_HISTORY_TEXT,
                callHistoryText.getId(),
                callHistoryText.getVersion(),
                ()-> callHistoryTextRepository.save(callHistoryText));

        if(!flag){
            result.setCode(GlobalStatic.CODE_N);
            result.setMsg("保存出错");
            return result;
        }

        result.setCode(GlobalStatic.CODE_1);
        result.setMsg("成功");

        return result;
    }

    /**
     * 修改通话内容
     * @param updateMap
     * @param callHistoryTextId
     * @param version
     * @return
     */
    public WebResult updateCallHistoryText(Map<String,Object> updateMap, String callHistoryTextId, Long version){
        WebResult result = new WebResult();
        updateMap.put("version",version + 1);
        boolean flag = checkVersionAndUpdateData(CallDataRedisVersionKey.TABLE_CALL_HISTORY_TEXT,
                CallDataTables.CALL_HISTORY_TEXT,
                callHistoryTextId,
                version,
                ()-> callHistoryTextRepository.updateSomeFields(callHistoryTextId,CallHistoryText.class,updateMap));

        if(!flag){
            result.setCode(GlobalStatic.CODE_N);
            result.setMsg("保存出错");
            return result;
        }

        result.setCode(GlobalStatic.CODE_1);
        result.setMsg("成功");

        return result;
    }

    /**
     * 分页查询通话内容
     * @param boolQueryBuilder
     * @param sort
     * @param pageable
     * @return
     * @throws Exception
     */
    public Page<CallHistoryText> queryCallHistoryPageList(BoolQueryBuilder boolQueryBuilder, FieldSortBuilder sort, Pageable pageable, SourceFilter sourceFilter)throws Exception{
        if(pageable == null){
            pageable = PageRequest.of(0,10);
        }
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder().withPageable(pageable);
        if(boolQueryBuilder !=null && boolQueryBuilder.hasClauses()){
            builder.withQuery(boolQueryBuilder);
        }
        if(sort != null){
            builder.withSort(sort);
        }
        if(sourceFilter!=null){
            builder.withSourceFilter(sourceFilter);
        }
        Page<CallHistoryText> page = callHistoryTextRepository.search(builder.build());
        return page;
    }


    /**
     * 根据map的条件查询CallHistoryTest
     * @param params
     * @return
     */
    public List<CallHistoryText> searchCallHistoryTextList(Map<String,Object> params){

        List<CallHistoryText> resultList=new ArrayList<>();

            QueryBuilder boolQueryBuilder = getBoolQueryBuilder(params);

            Iterator<CallHistoryText> iterator = callHistoryTextRepository.search(boolQueryBuilder).iterator();

            while (iterator.hasNext()){

                resultList.add(iterator.next());
            }

            //根据时间排序,这里只是权宜之计...........
            if (resultList.size()>0){
                resultList = resultList.stream().sorted(Comparator.comparing(CallHistoryText :: getCreateTime)).collect(Collectors.toList());
            }


        return resultList;
    };

    /**
     * 根據map中的參數拼接查詢條件
     * @return
     */
    public QueryBuilder getBoolQueryBuilder(Map<String,Object> params){

        BoolQueryBuilder builder = QueryBuilders.boolQuery();

        Set<String> paramKeys = params.keySet();

        if (paramKeys!=null&&paramKeys.size()>0) {

            for (String key : paramKeys) {

                switch (key) {

                    case "sourceCallHistoryId":

                        System.out.println(params.get("sourceCallHistoryId"));

                        builder.must(QueryBuilders.termQuery("sessionId", params.get("sourceCallHistoryId")));
                        break;
                }
            }
        }else {
            builder.must(QueryBuilders.matchAllQuery());
        }


        return builder;

    };
}
